package com.example.wenqujingdian.activity;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wenqujingdian.CustomerWebView;
import com.example.wenqujingdian.R;
import com.example.wenqujingdian.conast.AudioKey;
import com.example.wenqujingdian.utils.ToastUtil;
import com.vise.utils.handler.HandlerUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;


public class WebViewActivity3 extends AppCompatActivity {

    private CustomerWebView progressWebview;
    private Toolbar mToolbar;
    private TextView toolbar_tv;
    ImageButton btnPlay;
    ImageButton btnSoundType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //其他逻辑
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_web_view_tabbar);
        initView();
    }


    private void initView() {
        String url = getIntent().getStringExtra("url");
        String title = getIntent().getStringExtra("title");
        mToolbar = findViewById(R.id.toolbar);
        toolbar_tv = findViewById(R.id.title);

        btnPlay =   findViewById(R.id.playPaper);
        btnSoundType =   findViewById(R.id.soundType);

        final int width = btnPlay.getLayoutParams().width;
        final int height = btnPlay.getLayoutParams().height;

        btnPlay.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Log.i("focus", "btnPlay has focus ");
                    v.setBackgroundColor(Color.YELLOW);
                }else{
                    v.setBackgroundColor(Color.alpha(100));
                }
            }
        });
        btnSoundType.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    v.setBackgroundColor(Color.YELLOW);
                }else{
                    v.setBackgroundColor(Color.alpha(100));
                }
            }
        });

        progressWebview = findViewById(R.id.web_view);
        progressWebview.loadUrl(url);
        setUpToolbar(title);
        progressWebview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.e("webview日志", consoleMessage.message());
                return super.onConsoleMessage(consoleMessage);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                //使弹窗变toast
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                result.confirm();
                return true;
            }
        });
        WebViewClient webViewClient = new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url == null) return false;
                try {
                    if (!url.startsWith("http://") //微信
                            && !url.startsWith("https://") //支付宝

                    ) {
                        //不是规范开头直接returnfalse
                        return false;
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    Log.i("加载资源", "异常");
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                Log.i("加载资源", url);
                //处理http和https开头的url
                view.loadUrl(url);
                return true;
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //view.loadUrl(String.format(Locale.CHINA, "javascript:document.body.style.paddingTop='%fpx'; void 0", DensityUtil.px2dp(webView.getPaddingTop())));
                if (!zhuRu(view, url)) {
                    //  ToastUtil.showToast("网站url为: " + url);
                } else {
                    //ToastUtil.show("注入成功");
                }
            }
        };

        progressWebview.setWebViewClient(webViewClient);
        progressWebview.setInitialScale(100);   //100代表不缩放
        progressWebview.addJavascriptInterface(this, "webView");

    }

    //区分注入方式
    public boolean zhuRu(WebView webView, String url) {
        Map<String, String> urlMap = new LinkedHashMap<>();
        //人民日报
        urlMap.put("paper.people.com.cn/rmrb", "renMinRiBao");
        //解放军报
        urlMap.put("81.cn/jfjbmap", "jieFangJunBao");
        urlMap.put("81.cn/lj", "haiLuKong");
        urlMap.put("81.cn/hj", "haiLuKong");
        urlMap.put("81.cn/kj", "haiLuKong");
        urlMap.put("81.cn/yw", "haiLuKong");
        urlMap.put("81.cn/gfbmap", "zhongGuoGuoFangBao");
        //环球时报
        urlMap.put("huanqiu", "huanQiuShiBao");
        //参考消息
        urlMap.put("cankaoxiaoxi", "canKaoXiaoXi");
        //北京日报
        urlMap.put("bjd.com", "beiJingRiBao");
        //健康报
        urlMap.put("newpaper.dahe.cn/dhjkb", "jianKangBao");
        urlMap.put("jwb.com", "laoNianBao");
        urlMap.put("jjckb.cn/", "jingJiCanKaoBao");
        //老年报
        urlMap.put("paper.ce.cn", "jingJiRiBao");
        urlMap.put("gmw.cn", "guangMingRiBao");
        //urlMap.put("mrdx.cn", "xinHuaDianXun");
        urlMap.put("bao.laoren.com", "kuaiLeLaoRenBao");
        urlMap.put("workercn.cn", "gongRenRiBao");
        urlMap.put("legaldaily.com.cn", "faZhiRiBao");
        urlMap.put("szb.farmer.com.cn", "nongMinRiBao");
        urlMap.put("dzb.whb.cn", "wenHuiBao");
        urlMap.put("chinafilmnews.cn", "zhongGuoDianYingBao");
        urlMap.put("chinatimes.net.cn/article", "huaXiaShiBao");


        if(url.contains("http://vertical.591adb")) {
            if (url.contains("journal/article")) {
                urlMap.put("vertical.591adb.cn/journal/article", "qikan");
            }else{
                return false;
            }
        }else{
            Log.e("mytest","-----baozhi-----");
            urlMap.put("/", "baozhi");
        }

        Set<String> keys = urlMap.keySet();
        for (String key : keys) {
            if (url.contains(key)) {
                //执行特殊注入
                //ToastUtil.show("适配语音注入成功");
                loadLocalJS(webView, "jquery.min");
                loadLocalJS(webView, "baseDuBao");
                Log.e("mytest","----------"+urlMap.get(key));
                loadLocalJS(webView, urlMap.get(key));
                return true;
            }
        }
        return false;

    }

    public String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open("duBaoScript/" + fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null) {
                if (!line.trim().startsWith("//")) {
                    Result += line + "\n";
                }
            }
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void loadJsFile(WebView webView, String content) {
        String js = "var newscript = document.createElement(\"script\");";
        js += "newscript.textContent=\"" + content + "\";";
        js += "document.body.appendChild(newscript);";
        webView.loadUrl("javascript:" + js);
    }

    //注入本地js
    public void loadLocalJS(WebView webView, String jsFileName) {
        String js = getFromAssets(jsFileName + ".js");
        if (null == js) {
            ToastUtil.show("读取出错");
        }
        Log.e("注入js", js.replace("\n", ""));
        webView.loadUrl("javascript:" + js);
    }

    private void setUpToolbar(String title) {
        mToolbar.setTitle("");
        toolbar_tv.setText(title);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             /*   if (progressWebview.canGoBack()) {
                    progressWebview.goBack();//返回上一页面
                } else {
                    finish();
                }*/
                progressWebview.destroy();
                finish();
            }
        });

    }

    /**
     * 方法描述：改写物理按键——返回的逻辑
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (progressWebview.canGoBack()) {
                progressWebview.goBack();//返回上一页面
                return true;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void play(View view) {
        progressWebview.loadUrl("javascript:duBao.playFun()");
    }

    public void soundType(View view) {
        progressWebview.loadUrl("javascript:duBao.changeSound()");
    }

    @JavascriptInterface
    public void changePlay(final String msg) {
        HandlerUtil.runOnUiThread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void run() {
                if (msg.equals("播放")) {
                    btnPlay.setImageDrawable(getDrawable(R.mipmap.play));
                } else {
                    btnPlay.setImageDrawable(getDrawable(R.mipmap.stop));
                }
            }
        });
    }

    @JavascriptInterface
    public void changeSound(final String msg) {
        HandlerUtil.runOnUiThread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void run() {

                if (msg.contains("女")) {
                    btnSoundType.setImageDrawable(getDrawable(R.mipmap.nv));
                } else {
                    btnSoundType.setImageDrawable(getDrawable(R.mipmap.nan));
                }
            }
        });

    }
    @JavascriptInterface
    public String getKey() {
        return AudioKey.key;
    }

    @JavascriptInterface
    public void showBtn() {
        HandlerUtil.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btnPlay.setVisibility(View.VISIBLE);
                btnSoundType.setVisibility(View.VISIBLE);
            }
        });

    }

    //结束webview避免退出还读
    public void destroyWebView() {
        progressWebview.destroy();
    }



    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        destroyWebView();
    }
}
